package com.chagee.store.operation.server.transfer;

import com.chagee.store.operation.api.enums.CommentTypeEnum;
import com.chagee.store.operation.common.annotation.FiledDesc;
import com.chagee.storeManagement.api.event.enums.DeviceLineTypeEnum;
import com.chagee.storeManagement.api.event.enums.StoreBusinessStatusEnum;
import com.chagee.storeManagement.api.event.enums.StoreCategoryEnum;
import com.chagee.storeManagement.api.event.enums.StoreStatusEnum;
import com.chagee.storeManagement.api.event.enums.StoreTypeEnum;
import org.apache.commons.lang3.tuple.Pair;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Objects;

public class ChangeInfoTransfer {

	/**
	 * 变更前后数据变化
	 * @param oldData 历史数据
	 * @param newData 新数据
	 * @return map
	 */
	public static <T> Pair<String , String> getChangeInfo(T oldData, T newData) {
		HashMap<String, String> changeMap = new HashMap<>();
		StringBuilder changeBefore = new StringBuilder();
		StringBuilder changeAfter = new StringBuilder();

		Field[] fields = oldData.getClass().getDeclaredFields();
		for (Field field : fields) {

			FiledDesc annotation = field.getAnnotation(FiledDesc.class);
			if (Objects.isNull(annotation)) {
				continue;
			}

			field.setAccessible(true);
			Object ov;
			Object nv;
			try {
				ov = field.get(oldData);
				nv = field.get(newData);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}

			if (Objects.equals(ov, nv) || Objects.isNull(nv)) {
				continue;
			}

			ov = transferEnum(ov, annotation.type());
			nv = transferEnum(nv, annotation.type());

			changeAfter.append(annotation.value()).append(":").append(nv).append(",");
			// nv nonnull and ov nonnull update
			changeBefore.append(annotation.value()).append(":").append(Objects.nonNull(ov) ? ov : "-").append(",");

		}

		if (changeBefore.length() > 0) {
			changeMap.put("changeBefore", changeBefore.substring(0, changeBefore.length() - 1));
		} else {
			changeMap.put("changeBefore", changeBefore.toString());
		}

		if (changeAfter.length() > 0) {
			changeMap.put("changeAfter", changeAfter.substring(0, changeAfter.length() - 1));
		} else {
			changeMap.put("changeAfter", changeAfter.toString());
		}

		return Pair.of(changeMap.get("changeBefore"), changeMap.get("changeAfter"));
	}

	private static Object transferEnum(Object bean, FiledDesc.ENUM_TYPE type) {
		switch (type) {
			case NONE:
				break;

			case COMMENT_TYPE:
				if (Objects.nonNull(bean)) {
					CommentTypeEnum commentTypeEnum = CommentTypeEnum.queryByType((String) bean);
					if (Objects.nonNull(commentTypeEnum)) {
						bean = commentTypeEnum.getDesc();
					}
				}
				break;
			case COMMENT_CONFIG:
				int status = (int) bean;
				bean = "禁用";
				if (Objects.equals(1, status)) {
					bean = "启用";
				}
				break;

		}
		return bean;
	}
}
